package com.team.engine.common.view;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * 分页标签，配置信息写在com.team.engine.common.view.common.tld中，name是subpage<br/>
 * 用法：<br/>
 * <%@taglib prefix="common" uri="/WEB-INF/classes/com/team/engine/common/view/common.tld" %>
 * <common:subpage thisPage="${requestScope.thisPage }" totalPage="${requestScope.totalPage }" href="user/get|get.do|from|jthm|...)" />
 * @author MengLH
 * @data 2010-10-20
 */
public class SubPageTag extends TagSupport {

	private static final long serialVersionUID = -6795654640668384584L;

	/**
	 * 总页数
	 */
	private Integer totalPage;
	
	/**
	 * 当前页码
	 */
	private Integer thisPage;
	
	/**
	 * 请求链接
	 */
	private String href;
	
	/**
	 * 页码参数名
	 */
	private String pageflag;
	
	/**
	 * 转义的双引号符
	 */
	private static final String QUOT = "\"";

	public void setPageflag(String pageflag) {
		this.pageflag = pageflag;
	}

	public void setHref(String href) {
		this.href = href;
	}

	public void setTotalPage(Integer totalPage) {
		this.totalPage = totalPage;
	}

	public void setThisPage(Integer thisPage) {
		this.thisPage = thisPage;
	}

	@Override
	public int doAfterBody() throws JspException {
		return this.SKIP_BODY;
	}

	@Override
	public int doEndTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			if (totalPage == 1) {
				out.print("就一页，分啥分");
				return this.EVAL_PAGE;
			}
			
			if (thisPage < 1)
				thisPage = 1;
			
			if (thisPage > totalPage)
				thisPage = totalPage;

			this.pageflag = pageflag == null || pageflag.trim().length() == 0 ? "page" : pageflag;
			
			// 拼串结果类同这句，<a href="fileList.jhtm?page=
			String strG = "<a href=" + QUOT + href + "?" + pageflag + "=";

			if (this.thisPage > 1) {
				String str = strG + (thisPage - 1) + QUOT + ">上一页&nbsp;</a>";
				out.print(str);
			} // 拼串结果类同这句，<a href="fileList.jhtm?page=${thisPage-1 }">上一页</a>

			for (int i = 1; i <= this.totalPage; i++) {
				String str = null;
				if (thisPage != i) {
					str = strG + i + QUOT + ">" + i + "</a>";
					out.print(str);
					// 拼串结果类同这句，<a href="fileList.jhtm?page=${page }">${page}</a>
				} else
					out.print(i);

				out.print("&nbsp;");
			}

			if (thisPage < totalPage) {
				String str = strG + (thisPage + 1) + QUOT + ">下一页</a>";
				out.print(str);
			} // 拼串结果类同这句，<a href="fileList.jhtm?page=${thisPage+1 }">下一页</a>

		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return this.EVAL_PAGE;
	}

	@Override
	public int doStartTag() throws JspException {
		
		return this.SKIP_BODY;
	}

}
